package com.apex.aolonfitdemo.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.aolonfit.AolonFitManager;
import com.apex.aolonfitdemo.R;
import com.apex.aolonfitdemo.databinding.ActivityMainBinding;
import com.apex.ax_bluetooth.model.EABleDevice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding activityMainBinding;
    private ItemAdapter itemAdapter;
    private ScanDeviceListener scanDeviceListener;
    Map<String, EABleDevice> deviceMap = new HashMap<>();
    Timer mTimer;
    int count;
    Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x01) {
                count += 1;
                if (!deviceMap.isEmpty()) {
                    List<EABleDevice> dList = new ArrayList<>(deviceMap.values());
                    Collections.sort(dList, new Comparator<EABleDevice>() {
                        @Override
                        public int compare(EABleDevice o1, EABleDevice o2) {
                            if (o1 != null && o2 != null) {
                                if (o1.getRssi() > o2.getRssi()) {
                                    return -1;
                                } else if (o1.getRssi() == o2.getRssi()) {
                                    return 0;
                                } else {
                                    return 1;
                                }
                            }
                            return 0;
                        }
                    });
                    itemAdapter = new ItemAdapter(dList);
                    activityMainBinding.deviceList.setAdapter(itemAdapter);

                }
                if (count <= 5) {
                    sendEmptyMessageDelayed(0x01, 1000);
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activityMainBinding.deviceList.setLayoutManager(linearLayoutManager);

    }

    @Override
    protected void onStart() {
        super.onStart();
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            permissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
        }
        requestPermissions(permissionList.toArray(new String[0]), 100);

    }

    @Override
    protected void onDestroy() {
        activityMainBinding = null;
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        stopBluetoothScan();
        super.onDestroy();
    }

    class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHold> {
        List<EABleDevice> deviceList;

        public ItemAdapter(List<EABleDevice> deviceList) {
            this.deviceList = deviceList;
        }

        @NonNull
        @Override
        public ItemHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.adapter_main_recyclerview, parent, false);
            return new ItemHold(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull ItemHold holder, int position) {
            if (deviceList == null && deviceList.isEmpty()) {
                return;
            }
            EABleDevice eaBleDevice = deviceList.get(position);
            if (TextUtils.isEmpty(eaBleDevice.getDeviceName())) {
                holder.nameText.setText(getString(R.string.unknown));
            } else {
                holder.nameText.setText(eaBleDevice.getDeviceName());
            }
            holder.serialText.setText(eaBleDevice.getDeviceSign());
            holder.addressText.setText(eaBleDevice.getDeviceAddress());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                    intent.putExtra("blue_address", eaBleDevice.getDeviceAddress());
                    startActivity(intent);
                    finish();
                }
            });
        }

        @Override
        public int getItemCount() {
            return deviceList == null ? 0 : deviceList.size();
        }

        class ItemHold extends RecyclerView.ViewHolder {

            TextView nameText;

            TextView addressText;

            TextView serialText;

            public ItemHold(@NonNull View itemView) {
                super(itemView);
                nameText = itemView.findViewById(R.id.device_name);
                addressText = itemView.findViewById(R.id.device_address);
                serialText = itemView.findViewById(R.id.device_serial);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null) {
            boolean hasPermission = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    hasPermission = false;
                    break;
                }

            }
            if (!hasPermission) {
                Toast.makeText(MainActivity.this, getString(R.string.location_permission), Toast.LENGTH_SHORT).show();
                return;
            }
            if (mTimer==null) {
                scanBluetoothDevice();
            }
        }
    }

    @SuppressLint("MissingPermission")
    private void scanBluetoothDevice() {
        if (scanDeviceListener == null) {
            scanDeviceListener = new ScanDeviceListener();
        }
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();
            BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            Log.e("MainActivity", "开始扫描蓝牙");
            bluetoothLeScanner.startScan(null, settings, scanDeviceListener);
            if (mTimer == null) {
                mTimer = new Timer();
            }
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    stopBluetoothScan();

                }
            }, 5000);
            mHandler.sendEmptyMessageDelayed(0x01, 1000);
        }

    }

    class ScanDeviceListener extends ScanCallback {
        @SuppressLint("MissingPermission")
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            if (result != null) {
                BluetoothDevice bluetoothDevice = result.getDevice();
                if (bluetoothDevice != null) {
                    EABleDevice eaBleDevice = new EABleDevice();
                    eaBleDevice.setDeviceAddress(bluetoothDevice.getAddress());
                    eaBleDevice.setDeviceName(bluetoothDevice.getName());
                    eaBleDevice.setRssi(result.getRssi());
                    eaBleDevice.setType(bluetoothDevice.getType());
                    deviceMap.put(bluetoothDevice.getAddress(), eaBleDevice);
                }
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }


    }

    @SuppressLint("MissingPermission")
    private void stopBluetoothScan() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.stopScan(scanDeviceListener);
            }
        }
    }
}
